package com.example.concurrentprogramming8016.future.completablefuture;


import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @author liyanhao
 * @Date 2023-01-08 21:05
 * 将两个线程任务获取结果的速度相比较，按一定的规则进行下一步处理
 */
public class ApplyToEitherDemo {
    public static void main(String[] args) {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            int number = new Random().nextInt(10) + 1;
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("第一阶段 " + number);
            return number;
        });
        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            int number = new Random().nextInt(10) + 1;
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("第二阶段 " + number);
            return number;
        });

        completableFuture.acceptEither(completableFuture1, new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                System.out.println("最快的结果是:"+integer);
            }
        }).join();

    }
}
